package com.bkhc.product.repository;

import com.bkhc.product.entity.Spec;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface SpecRepository extends JpaRepository<Spec,String> , JpaSpecificationExecutor<Spec> {

    default Page<Spec> findAll(Spec spec, Pageable pageable){
     return findAll(new Specification<Spec>() {
         @Override
         public Predicate toPredicate(Root<Spec> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
             List<Predicate> predicate = new ArrayList<>();
             if(!StringUtils.isEmpty(spec.getSpecCode())){
                 predicate.add(criteriaBuilder.equal(root.get("specCode").as(String.class), spec.getSpecCode()));
             }
             if(!StringUtils.isEmpty(spec.getSpecName())){
                 predicate.add(criteriaBuilder.like(root.get("specName").as(String.class),"%"+spec.getSpecName()+"%"));
             }
                 if(!StringUtils.isEmpty(spec.getStatus())){
                 predicate.add(criteriaBuilder.equal(root.get("status").as(String.class),spec.getStatus()));
             }
             Predicate[] pre = new Predicate[predicate.size()];

             return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
         }
     },pageable);


    }
    Spec findBySpecName(String specName);
    Spec findBySpecCode(String specCode);
    void deleteBySpecCode(String specCode);
    @Query("select s from Spec s where s.productCode = :productCode order by s.sort")
    List<Spec> findByProductCode(@Param("productCode") String productCode);

    void deleteByProductCode(String productCode);
    @Query("select s from Spec s where s.productCode in  (:productCodes) order by s.sort")
    List<Spec> findInProductCode(@Param("productCodes") List<String> productCodes);
}
